"use client"

import { useState, useEffect } from "react"
import { getClientAppointments, getCoachAppointments,getCourseAppointmentClients } from "@/lib/appointmentService"
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { format } from "date-fns"
import { Badge } from "@/components/ui/badge"
import { Label } from "@/components/ui/label"
import EmptyState from "@/components/EmptyState"
import { CalendarDays, MapPin, User2 } from "lucide-react"

export default function AppointmentList({ user, coaches, clients, campuses, courts }) {
    // 获取预约列表
    const [appointments, setAppointments] = useState([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        const fetchAppointments = async () => {
            try {
                let appointments = user.role === 'client'
                    ? await getClientAppointments(user.id, { status: 'pending' })
                    : await getCoachAppointments(user.id, { status: 'pending' });
                if (user.role === 'coach') {
                    appointments = appointments.filter(appointment => appointment.status === 'pending');
                    appointments = await Promise.all(appointments.map(async (appointment) => {
                        appointment.clients = await getCourseAppointmentClients(appointment.id);
                        return appointment;
                    }));
                }
                setAppointments(appointments);
            } catch (error) {
                console.error('获取预约列表失败:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchAppointments();
    }, [user])

    const AppointmentCard = ({ appointment }) => {
        const getStatusBadge = (status) => {
            const statusMap = {
                'pending': { label: '待上课', variant: 'outline' },
                'confirmed': { label: '已确认', variant: 'default' },
                'completed': { label: '已完成', variant: 'secondary' },
                'cancelled': { label: '已取消', variant: 'destructive' }
            };
            const statusInfo = statusMap[status] || { label: status, variant: 'outline' };
            return <Badge className="text-xs md:text-base" variant={statusInfo.variant}>{statusInfo.label}</Badge>;
        };

        return (
            <Card className="mb-4">
                <CardHeader>
                    <CardTitle className="flex items-center">
                        <div className="flex items-center">
                            <CalendarDays className="h-5 w-5 text-sm md:text-base" />
                            <span className="text-sm md:text-base">
                                {format(new Date(appointment.start_time), "MM月dd日 HH:mm")} -
                                {format(new Date(appointment.end_time), "HH:mm")}
                            </span>
                        </div>
                        {getStatusBadge(appointment.status)}
                    </CardTitle>
                </CardHeader>
                <CardContent className="space-y-2">
                    <div className="flex items-center gap-2">
                        <MapPin className="h-4 w-4 text-muted-foreground" />
                        <span>
                            {campuses.find(campus => campus.id === appointment.branch_campus_id)?.name} - {courts.find(court => court.id === appointment.court_id)?.name}
                        </span>
                    </div>
                    {user.role === 'client' && (
                        <div className="flex items-center gap-2">
                            <User2 className="h-4 w-4 text-muted-foreground" />
                            <span>教练：{coaches.find(coach => coach.id === appointment.coach_id)?.name}</span>
                        </div>
                    )}
                    {user.role === 'coach' && appointment.clients?.length > 0 && (
                        <div className="flex items-center gap-2">
                            <User2 className="h-4 w-4 text-muted-foreground" />
                            <span>学员：{appointment.clients.map(client => client.client.name).join(', ')}</span>
                        </div>
                    )}
                    {appointment.memo && (
                        <div className="mt-2 text-sm text-muted-foreground">
                            <Label>备注：</Label>
                            <p>{appointment.memo}</p>
                        </div>
                    )}
                </CardContent>
            </Card>
        );
    };

    if (loading) {
        return <div className="flex justify-center items-center p-8">加载中...</div>;
    }

    if (!appointments.length) {
        return <EmptyState message={`暂无${user.role === 'client' ? '预约记录' : '课程安排'}`} />;
    }

    return (
        <div className="space-y-4">
            <h2 className="text-xl font-semibold mb-4">
                {user.role === 'client' ? '我的课程' : '课程安排'}
            </h2>
            <div>
                {appointments.map(appointment => (
                    <AppointmentCard
                        key={appointment.id}
                        appointment={appointment}
                    />
                ))}
            </div>
        </div>
    );
}